/* eslint-disable no-unused-vars */
import './index.less'
import { Table, Empty } from 'ant-design-vue'
import VueDraggableResizable from 'vue-draggable-resizable'

export default {
  name: 'StandardTable',
  props: {
    columns: {
      type: Array,
      required: true
    },
    dataSource: {
      type: Array,
      required: true
    },
    pagination: {
      type: [Object, Boolean]
    },
    alert: {
      type: [Object, Boolean],
      default: null
    },
    bordered: {
      type: Boolean
    },
    rowKey: {
      type: String,
      default: 'id'
    },
    size: {
      type: String,
      default: 'small'
    },
    scroll: {
      type: Object,
      default: () => { return {} }
    },
    rowSelection: {
      type: Object,
      default: null
    },

    rowClassName: {
      type: Function,
      default: (record, index) => {
        if (index % 2 === 0) {
          return 'odd'
        }
      }
    }
  },
  data () {
    const draggingState = {}
    this.columns.forEach(col => {
      if (col.draw) {
        draggingState[col.dataIndex] = col.width || 0
      }
    })
    this.components = {
      header: {
        cell: this.resizeableTitle
      }
    }
    // 是否存在多选
    this.isRowSelection = Object.keys(this.rowSelection || {})
    return {
      draggingState,
      selectedRowKeys: [],
      selectedRows: [],
      needTotalList: [],
      isLoading: true
    }
  },
  watch: {
    dataSource (val) {
      this.isLoading = false
    }
  },
  mounted () {
  },
  methods: {
    resizeableTitle (h, props, children) {
      const { columns, draggingState } = this
      let isDrag = false
      const { key, ...restProps } = props
      // 获取正在拖动的columnsItem
      const col = columns.find(col => {
        let draw = col.draw ? col.dataIndex : null
        return draw === key
      })
      if (!col) {
        return <th {...restProps}>{...children}</th>
      }
      // 获取columns点击事件
      if (restProps.on && restProps.on.click) {
        let clickFunc = restProps.on.click
        restProps.on.click = (event) => {
          if (isDrag) {
            return
          }
          clickFunc(event)
        }
      }
      // 获取正在拖动的key
      const colIndex = columns.findIndex(col => {
        let draw = col.draw ? col.dataIndex : null
        return draw === key
      })
      const onDrag = (x) => {
        isDrag = true
        const keysColIndex = this.isRowSelection ? colIndex + 1 : colIndex
        let parentDom = this.$refs.tableCommon.querySelectorAll('colgroup col')[keysColIndex]
        parentDom.style.width = x + 'px'
      }
      // 释放columns点击事件
      const onDragstop = () => {
        setTimeout(() => {
          isDrag = false
        }, 300)
      }
      return (
        <th {...restProps} class="resize-table-th">
          <span> {...children}</span>
          <VueDraggableResizable
            key={col.key}
            class="table-draggable-handle"
            w={10}
            x={draggingState[key] || col.width}
            z={1}
            axis="x"
            draggable={true}
            resizable={false}
            onDragging={onDrag}
            onDragstop={onDragstop}
          ></VueDraggableResizable>
        </th>
      )
    },
    /**
 * 用于更新已选中的列表数据 total 统计
 * @param selectedRowKeys
 * @param selectedRows
 */
    updateSelect (selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows
      this.selectedRowKeys = selectedRowKeys
      const list = this.needTotalList
      this.needTotalList = list.map(item => {
        return {
          ...item
        }
      })
    },
    /**
     * 清空 table 已选中项
     */
    clearSelected () {
      if (this.rowSelection) {
        this.rowSelection.onChange([], [])
        this.updateSelect([], [])
      }
    },
    // 处理分页、排序、筛选变化
    handleTableChange (pagination, filters, sorter) {
      this.isLoading = true
      const { current, pageSize } = pagination
      let params = {
        pageNum: current,
        pageSize
      }

      this.$emit('change', params, sorter, filters)
    },
    customizeRenderEmpty () {
      return (<Empty description={false} />)
    },
    // 用于添加合计行
    addFooterSum (footerSumVnode) {
      if (!footerSumVnode || footerSumVnode.length) return
      let parentDom = this.$refs.tableCommon.querySelectorAll('.ant-table-tbody')[0]
      let lastAddDom = this.$refs.tableCommon.querySelectorAll('.lastFooterSum')[0]
      let objParents = document.createElement('div')
      let VnodeToDom = footerSumVnode ? this.mount(footerSumVnode, objParents) : []
      VnodeToDom.className = 'lastFooterSum'
      this.$nextTick(() => {
        const { total } = this.pagination
        if (total === 0 && lastAddDom) {
          lastAddDom.remove()
          return
        }
        // 添加keys
        VnodeToDom.setAttribute('data-row-key', total + 1)
        if (lastAddDom) {
          lastAddDom.remove()
        }
        parentDom.appendChild(VnodeToDom)
      })
    },
    // 将vnode转为真实DOM
    mount (vnode, container) {
      // 1. 将tag转为标签
      const el = vnode.el = document.createElement(vnode.tag || 'span')
      // 2. 给标签设置对应的属性
      if (vnode.data) {
        for (const key in vnode.data) {
          const value = vnode.data[key]
          // 点击事件
          if (key.startsWith('on')) {
            for (let o in value) {
              el.addEventListener(o, value[o])
            }
          } else if (key.startsWith('attrs')) {
            for (let o in value) {
              el.setAttribute(o, value[o])
            }
          } else {
            el.setAttribute(key, value)
          }
        }
      }
      // 3. 处理children
      if (vnode.children) {
        if (typeof vnode.children === 'string' || typeof vnode.children === 'number') {
          el.textContent = vnode.children
        } else {
          vnode.children.forEach(item => {
            this.mount(item, el)
          })
        }
      } else {
        el.textContent = vnode.text
      }
      // 4. 将节点挂载到节点上
      container.appendChild(el)
      return container.children[0]
    }
  },
  render () {
    const props = {}
    Object.keys(Table.props).forEach(k => {
      // 数据处理
      if (k === 'columns') {
        if (this.columns) {
          this.columns.forEach(item => {
            if (item.dataIndex === '_index') {
              item.customRender = (text, record, index) => {
                return index + 1
              }
            }
            if (item.dataIndex === 'number') {
              item.customRender = (text, record, index) => {
                const { pageNum, pageSize } = this.pagination
                return (pageNum - 1) * pageSize + index + 1
              }
            }
            let customRender = item.scopedSlots && item.scopedSlots.customRender
            if (!item.customRender && !item.tooltip && !customRender) {
              item.customRender = (text) => {
                if (text === null || text === undefined) {
                  return ''
                }
                let tooltip = item.align === 'center' ? 'top' : item.align === 'right' ? 'topRight' : 'topLeft'
                return <a-tooltip placement={tooltip} title={text}><div class="ell">{text}</div></a-tooltip>
              }
            }
            // 表格全部居中
            item.align = 'center'
          })
        }
      }
      // 分页
      if (k === 'pagination') {
        if (this.pagination) {
          const { total = 0, pageNum = 1, pageSize = 10 } = this.pagination
          props[k] = { ...this.pagination, total, pageSize, ...{ current: pageNum } }
        } else {
          props[k] = false
        }
        return props[k]
      }
      // 选中
      if (k === 'rowSelection') {
        if (this.rowSelection) {
          // 绑定 rowSelection 事件
          props[k] = {
            ...this.rowSelection,
            selectedRows: this.selectedRows,
            selectedRowKeys: this.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
              this.updateSelect(selectedRowKeys, selectedRows)
              typeof this[k].onChange !== 'undefined' && this[k].onChange(selectedRowKeys, selectedRows)
            }

          }
          return props[k]
        } else if (!this.rowSelection) {
          // 如果没打算开启 rowSelection 则清空默认的选择项
          props[k] = null
          return props[k]
        }
      }
      this[k] && (props[k] = this[k])
      return props[k]
    })
    const { rowSelection, handleTableChange, rowKey, isLoading, components } = this

    return (
      <div ref="tableCommon" class="standardTable">
        <Table
          {...{ props, scopedSlots: { ...this.$scopedSlots } }}
          rowKey={rowKey}
          loading={isLoading}
          rowSelection={rowSelection}
          components={components}
          onchange={handleTableChange}>
          {Object.keys(this.$slots).map(name => <template slot={name}>
            {this.$slots[name]}
          </template>)}
        </Table>
      </div >)
  }
}
